<template>
    <div class="page-container">
        <div class="card">
            <div class="split">
                <div style="max-width: 80%;">
                    <el-input clearable @clear="load()" class="card-input" v-model="searchData.id"
                        v-if="userStore.imAdmin()" placeholder="请输入作者id查询" prefix-icon="Search"
                        @keyup.enter="load()"></el-input>
                    <el-input clearable @clear="load()" class="card-input" v-model="searchData.title"
                        placeholder="请输入标题查询" prefix-icon="Search" @keyup.enter="load()"></el-input>
                    <el-input clearable @clear="load()" class="card-input" v-model="searchData.content"
                        placeholder="请输入内容查询" prefix-icon="Search" @keyup.enter="load()"></el-input>
                    <el-date-picker class="card-button" v-model="searchData.selectDate" type="daterange"
                        range-separator="至" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期" />
                    <el-select v-model="searchData.categoryId" placeholder="请选择分类" class="card-input" clearable
                        @clear="load()">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.categoryName"
                            :value="item.id" />
                    </el-select>
                    <el-select v-model="searchData.state" placeholder="请选择发布状态" class="card-input" clearable
                        @clear="load()">
                        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-button class="card-button" type="primary" @click="load()">查 询</el-button>
                    <el-button class="card-button" @click="resetSearch()">重 置</el-button>
                </div>
                <div>
                    <el-button class="card-button" type="primary" @click="handleAdd()">发布文章</el-button>
                </div>
            </div>
        </div>
        <!-- 数据显示 -->
        <div class="card">
            <el-table :data="tableData" style="width: 100%;" max-height="60vh">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="55" type="index" />
                <el-table-column label="用户名称" v-if="userStore.imAdmin()" prop="nickName" />
                <el-table-column label="用户id" width="70" v-if="userStore.imAdmin()" prop="createId" />
                <el-table-column label="标题" prop="title">
                    <template #default="scope">
                        <el-text truncated>
                            {{ scope.row.title }}
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column label="封面图" prop="coverImg" width="68">
                    <template #default="scope">
                        <el-image v-if="scope.row.coverImg" :src="scope.row.coverImg" class="littlePic"
                            :preview-src-list="[scope.row.coverImg]" :preview-teleported="true" />
                    </template>
                </el-table-column>
                <el-table-column label="正文内容" prop="content" min-width="500">
                    <template #default="scope">
                        <el-text truncated>
                            <el-link type="primary" underline="never" @click="showAllContent(scope.row.content)">{{ scope.row.content
                            }}</el-link>
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column label="文章分类" prop="categoryName" />
                <el-table-column label="发布时间" prop="updateTime" min-width="120" />
                <el-table-column label="发布状态" prop="state" />
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button style="margin-right: 5px;" type="primary" icon="Edit" circle plain
                            @click="handleEdit(scope.row)"></el-button>
                        <el-button type="danger" icon="Delete" circle plain
                            @click="handleDel(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty style="height: 100%;" description="没有查询到数据" />
                </template>
            </el-table>
        </div>
        <!-- 分页 -->
        <div class="card">
            <el-pagination v-model:current-page="paginationData.pageNum" v-model:page-size="paginationData.pageSize"
                :page-sizes="[10, 15, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
                :total="paginationData.total" @change="load()" />
        </div>
        <!-- 添加抽屉组件 -->

        <el-drawer v-model="drawerData.drawerVisible" :title="drawerData.title" direction="rtl" size="50%">
            <el-form :ref="formRef" :rules="formRules" :model="drawerData.form" style="padding: 0 20px;">
                <el-form-item prop="title" label="文章标题">
                    <el-input v-model="drawerData.form.title" autocomplete="off" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item prop="categoryId" label="文章分类">
                    <el-select v-model="drawerData.form.categoryId" placeholder="请选择分类" class="card-input" clearable
                        @clear="load()" style="width: 200px;">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.categoryName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="coverImg" label="文章封面">
                    <el-upload action="/api/files/upload" :on-success="handleFileSuccess" :headers="header"
                        :show-file-list="false" list-type="picture" :before-upload="beforeUpload" :limit="1">
                        <el-image v-if="drawerData.form.oldcoverImg" :src="drawerData.form.oldcoverImg"
                            class="littlePic" />
                        <el-image v-if="drawerData.form.coverImg" :src="drawerData.form.coverImg"
                            class="littlePic" />
                        <el-button v-else type="primary">点击上传图片</el-button>
                    </el-upload>
                </el-form-item>
                <!-- 使用quill富文本编辑器 -->
                <el-form-item prop="content" label="文章内容">
                    <div class="editor">
                        <!-- <quill-editor theme="snow" v-model:content="drawerData.form.content" content-type="html">
                        </quill-editor> -->

                        <Toolbar style="border: 1px solid #ccc; border-bottom: 0;" :editor="editorRef" :mode="mode" />
                        <Editor style="height: 40vh;border: 1px solid #ccc; overflow-y: hidden;"
                            v-model="drawerData.form.content" :defaultConfig="editorConfig" :mode="mode"
                            @onCreated="handleCreated" />
                        <!-- <MyWangEditor v-model:editorContent="drawerData.form.content" /> -->
                    </div>
                </el-form-item> </el-form>
            <template #footer>
                <div style="display: flex;justify-content: flex-start;margin-left: 20px;">
                    <el-button class="card-button" type="primary" @click="addArticle('已发布')">发布</el-button>
                    <el-button class="card-button" type="info" @click="addArticle('草稿')">草稿</el-button>
                </div>
            </template>
        </el-drawer>

        <!-- 展示所有正文内容 -->
        <el-dialog v-model="detail.contentVisible" title="文章详情" width="80%"  destroy-on-close top="5vh">
            <div style="padding:0 20px" v-html="detail.content"></div>
        </el-dialog>
    </div>
</template>



<script setup>
import {
    articlePageService,
    articleCategoryListService,
    articleAddService,
    articleDeleteService,
    articleUpdateService,
} from '@/api/article'
import { getConfig } from '@/utils/config';
import { useTokenStore } from '@/store/token';
import { beforeUpload } from '@/utils/function';
// 导入quill的组件和样式
// import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入wangeditor 相关内容
import '@wangeditor/editor/dist/css/style.css' // 引入css
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useUserStore } from '@/store/user';

const tokenStore = useTokenStore()
const userStore = useUserStore()

// wangEditor5 初始化开始
const editorRef = shallowRef()

const mode = 'default'
const wangHeader = ref({
    token: tokenStore.token
})

const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
    headers: wangHeader.value,
    server: getConfig('API_BASE_URL').replace(/\/?$/, '/') + 'files/wang/upload', // 服务端图片上传接口
    fieldName: 'file' // 服务端图片上传接口参数
}


// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})


// 记录editor实例
const handleCreated = (editor) => {
    editorRef.value = editor
}

// wangEditor5 初始化结束



// 分页数据
const paginationData = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

// 查询数据
const searchData = ref({
    selectDate: []
})

// 列表数据
const tableData = ref([])

// 状态字典
const stateOptions = ref([
    {
        label: '已发布',
        value: '已发布'
    },
    {
        label: '草稿',
        value: '草稿'
    },
])
// 分类字典，从文章分类表来
const categoryOptions = ref()

// 抽屉组件数据
const drawerData = ref({
    drawerVisible: false,
    title: '发布文章',
    form: {
        content: ' '
    }
})

// 获取所有文章分类
const getCategoryDict = async () => {
    const result = await articleCategoryListService()
    categoryOptions.value = result
}
getCategoryDict()

const load = async () => {
    if (userStore.imSuperAdmin()) {
        searchData.value.id = null
    } else {
        searchData.value.id = userStore.getUser().id
    }
    const params = {
        pageNum: paginationData.value.pageNum,
        pageSize: paginationData.value.pageSize,
        createId: searchData.value.id,
        title: searchData.value.title,
        content: searchData.value.content,
        categoryId: searchData.value.categoryId,
        state: searchData.value.state,
        startTime: searchData.value.selectDate ? searchData.value.selectDate[0] : null,
        endTime: searchData.value.selectDate ? searchData.value.selectDate[1] : null
    }
    const result = await articlePageService(params)
    tableData.value = result.list
    paginationData.value.total = result.total
}
load()

const resetSearch = () => {
    searchData.value = {}
    load()
}
const detail = ref({
    contentVisible: false,
    content: ''
})
// 展示所有正文内容
const showAllContent = (content) => {
    detail.value.contentVisible = true
    detail.value.content = content
}

const handleEdit = (row) => {
    drawerData.value.form = JSON.parse(JSON.stringify(row))
    drawerData.value.title = '更新文章'
    drawerData.value.drawerVisible = true
}

const handleDel = (id) => {
    ElMessageBox.confirm(
        '确认删除此文章分类？',
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        await articleDeleteService(id)
        ElMessage.success('删除成功')
        load()
    })
}

const handleAdd = () => {
    drawerData.value.form = {}
    drawerData.value.title = '发布文章'
    drawerData.value.drawerVisible = true
    drawerData.value.form.content = ' '
}

const addArticle = async (state) => {
    drawerData.value.form.state = state
    if (drawerData.value.form.id == null) {
        await articleAddService(drawerData.value.form)
    } else {
        await articleUpdateService(drawerData.value.form)
    }
    if (state == '已发布') {
        ElMessage.success("发布成功")
    } else {
        ElMessage.success("已保存为草稿")
    }
    drawerData.value.drawerVisible = false
    load()
}

// 上传图片的请求头
const header = ref({
    token: tokenStore.token
})

const handleFileSuccess = (res) => {
    if (res.code === '200') {
        ElMessage.success("图片上传成功")
        drawerData.value.form.coverImg = res.data
    } else {
        ElMessage({
            showClose: true,
            message: res.msg,
            type: 'warning',
            duration: 0,
        })
    }
}

const formRef = ref()
const formRules = ref({

    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
    ],
    categoryId: [
        { required: true, message: '请选择文章分类', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
    ]
})










</script>

<style scoped>
:deep(.el-drawer__header) {
    margin-bottom: 10px
}

/* 修改quill样式 */
.editor {
    width: 100%;
    height: 40vh;
}

:deep(.ql-container) {
    min-height: 200px;
}
</style>